﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.IdentityModel.Logging;
using Newtonsoft.Json;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace DFGK_WMS.Repository
{
    public class TTransferBinOrderRepository : BaseRepository<TTransferBinOrder>, ITTransferBinOrderRepository
    {
        public TTransferBinOrderRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        { 
        }

        /// <summary>
        /// 提交数据 （增加/修改/删除）
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool SubmitTransferBinOrderData(TTransferBinOrderDTO m)
        {
            //使用事务的原子性
            using (var trans = Context.Database.BeginTransaction())
            {
                try
                {
                    TTransferBinOrder tran = new TTransferBinOrder();
                    tran = Mapper.Map<TTransferBinOrder>(m);
                    bool isAdd = m.Id <= 0;
                    var com = Context.TCompanies.Where(c => c.Id == tran.CompanyId).FirstOrDefault();
                    #region 添加移库单
                    if (isAdd)
                    {
                        tran.CreateUserId = m.SubmitUserId;
                        tran.CreateUserName = m.SubmitUserName;
                        tran.CreateDate = DateTime.Now;
                        tran.ModifyDate = DateTime.Now;
                        tran.ModifyUserId = m.ModifyUserId;
                        tran.ModifyUserName = m.ModifyUserName;
                        tran.CompanyName = com.Name==null ? null : com.Name;
                        tran.Status = 0;
                    
                        Context.TTransferBinOrders.Add(tran);
                        Context.SaveChanges();
                        if (m.OrderDetailList != null && m.OrderDetailList.Count > 0)
                        {
                            foreach (var item in m.OrderDetailList)
                            {
                                item.OrderId = tran.Id;
                                item.OrderSn = tran.OrderSn;
                                item.CreateUserId = tran.CreateUserId;
                                item.CreateUserName = tran.CreateUserName;
                                item.CreateDate = tran.CreateDate;
                                item.ModifyUserId = tran.ModifyUserId;
                                item.ModifyUserName = tran.ModifyUserName;
                                item.ModifyDate = tran.ModifyDate;

                                #region 添加移库单明细
                                Context.TTransferBinOrderDetails.Add(item);
                                Context.SaveChanges();
                                
                                #endregion
                            }
                        }
                    }
                    #endregion

                    #region 修改/删除 移库单和移库单明细
                    else
                    {
                        #region 修改移库单
                        tran.ModifyDate = DateTime.Now;
                        tran.ModifyUserId = m.ModifyUserId;
                        tran.ModifyUserName = m.ModifyUserName;
                        tran.CompanyName = com.Name == null ? null : com.Name;
                        Context.TTransferBinOrders.Update(tran);
                        Context.SaveChanges();
                        #endregion

                        var listDetail = Context.TTransferBinOrderDetails.Where(t => t.OrderId == tran.Id).ToList();
                        if (listDetail != null && listDetail.Count > 0)
                        {
                            foreach (var item in listDetail)
                            {
                                Context.TTransferBinOrderDetails.Remove(item);
                            }
                            foreach (var item in m.OrderDetailList)
                            {
                                item.OrderId = tran.Id;
                                item.OrderSn = tran.OrderSn;
                                item.CreateUserId = tran.CreateUserId;
                                item.CreateUserName = tran.CreateUserName;
                                item.CreateDate = tran.CreateDate;
                                item.ModifyUserId = tran.ModifyUserId;
                                item.ModifyUserName = tran.ModifyUserName;
                                item.ModifyDate = tran.ModifyDate;

                                Context.TTransferBinOrderDetails.Add(item);
                                Context.SaveChanges();
                            }
                        }
                    }
                    #endregion
                    Context.SaveChanges();
                    //提交事务
                    trans.Commit();
                    return true;
                }
                catch (Exception)
                {
                    //事务回滚
                    trans.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 删除移库单
        /// </summary>
        /// <param name="tid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelTransferBinOrder(int tid)
        {
            var mobj = Context.TTransferBinOrders.Find(tid);
            if (mobj != null&&mobj.Status!=4)
            {

                Context.TTransferBinOrders.Remove(mobj);
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 获取可用仓位
        /// </summary>
        /// <param name="fromLocationId"></param>
        /// <param name="isPriorityFilling"></param>
        /// <param name="filterType"></param>
        /// <param name="toLogicalPartCode"></param>
        /// <returns></returns>
        public List<TCell> GetEnabledCellListByFromLocationId(string? toLogicalPartCode,int FromLocationId, bool isPriorityFilling = false, int filterType = 1)
        {
            var cellQuery = Context.TCells.AsNoTracking().ToList();
            var shelfQuery = Context.TShelves;
            var inventoryQuery = Context.TInventories;
            var inventory = inventoryQuery.Where(i => i.LocationId == FromLocationId).FirstOrDefault();

            if (inventory is null)
            {
                return null;
            }
            if (inventory.IsMultPallet == true)
            {
                toLogicalPartCode = "MultPallet";//花盘定死
            }
            List<int?> list=null;
            if(isPriorityFilling)
            {
                if (filterType == 1)
                {
                    list = inventoryQuery.Where(i => i.MaterialId == inventory.MaterialId && i.MaterialKeyId == inventory.MaterialKeyId && i.Status == 1).Select(i => i.LocationId).ToList();
                }
                else if (filterType == 2)
                {
                    list = inventoryQuery.Where(i => i.MaterialId == inventory.MaterialId && i.Status == 1).Select(i => i.LocationId).ToList();
                }
                else
                {
                    list = inventoryQuery.Where(i => i.Status == 1).Select(i => i.LocationId).ToList();
                }
                cellQuery = cellQuery.Where(c => list.Contains(c.Id) && c.Status == (int)EmCellStatus.Normal && c.IsLock == false && c.BusinessType == 0 && c.FullStatus == 0 && c.HeightType >= inventory.RealHeightType && c.LayerNo == inventory.LocationLayerNo && c.LineNo == inventory.LocationLineNo && c.ColumnNo > inventory.LocationColumnNo && c.DepthIndex == inventory.LocationDepth).ToList();
            }
            else
            {
                cellQuery = cellQuery.Where(c => c.Status == (int)EmCellStatus.Normal && c.FullStatus == 0 && c.IsLock == false && c.BusinessType == 0 && c.HeightType >= inventory.RealHeightType).ToList();
            }
            if (!string.IsNullOrEmpty(toLogicalPartCode))
            {
                cellQuery = cellQuery.Where(t => t.LogicalPartCode == toLogicalPartCode).ToList();
            }
            return cellQuery.OrderBy(c=>c.HeightType)
                .ThenBy(c=>c.LineNo)
                .ThenBy(c=>c.DistanceValue)
                .ThenBy(c=>c.LayerNo)
                .ThenBy(c=>c.ColumnNo)
                .ThenBy(c=>c.DepthIndex)
                .ToList();
        }

        /// <summary>
        /// 查询单个移库信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TTransferBinOrder GetTransferBinOrderById(int id)
        {
            return Context.TTransferBinOrders.Find(id);
            //TTransferBinOrderDTO Tdto = new TTransferBinOrderDTO();
            //Tdto = Mapper.Map<TTransferBinOrderDTO>(tran);
            //Tdto.OrderDetailList = Context.TTransferBinOrderDetails.Where(t => t.OrderId == tran.Id).ToList();

        }

        /// <summary>
        /// 查询全部移库单信息
        /// </summary>
        /// <param name="kname"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TTransferBinOrder> GetTransferBinOrderList(string? ordersn, DateTime? startTime, DateTime? endTime, int? companyId, int? status, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var list = Context.TTransferBinOrders.AsQueryable().ToList();
                list = list.OrderBy(t => t.CreateDate).ToList();
                // 查找公司
                if (!string.IsNullOrEmpty(ordersn))
                {
                    list = list.Where(x => x.OrderSn.Contains(ordersn)).ToList();
                }
                // 查找公司
                if (companyId != 0 && companyId is not null)
                {
                    list = list.Where(x => x.CompanyId == companyId).ToList();
                }

                // 查询状态
                if (status is not null)
                {
                    list = list.Where(x => x.Status == status).ToList();
                }

                // pda显示收获中和未收货的
                if (status is not null && status == 3)
                {
                    list = list.Where(x => x.Status != 2).ToList();
                }

                // 根据时间来筛选
                if (startTime != null && endTime != null)
                {
                    list = list.Where(x => x.CreateDate >= startTime && x.CreateDate <= endTime).ToList();
                }

                // pc显示收获中的在上面未收获的在下面
                if (status is not null && status == 4)
                {
                    list = list.Where(x => x.Status != 2).OrderByDescending(x => x.Status == 1).ThenByDescending(x => x.Status == 0).ToList();
                }
                totalCount = list.Count();
                return list.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 查看移库单的详细信息
        /// </summary>
        /// <param name="Id">移库单id</param>
        /// <returns></returns>
        public TTransferBinOrderDTO SelectTransferBinOrder(int Id)
        {
            var Trans = Context.TTransferBinOrders.FirstOrDefault(t => t.Id == Id);
            if (Trans != null)
            {
                TTransferBinOrderDTO dto = new TTransferBinOrderDTO();
                dto = Mapper.Map<TTransferBinOrderDTO>(Trans);
                dto.OrderDetailList = Context.TTransferBinOrderDetails.Where(t=>t.OrderId==dto.Id).ToList();
                return dto;
            }
            return null;
        }


        /// <summary>
        /// 修改移库单信息
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateTransferBinOrder(TTransferBinOrder t)
        {
            try
            {
                t.ModifyDate = DateTime.Now;
                t.ModifyUserId = t.ModifyUserId;
                t.ModifyUserName = t.ModifyUserName;
                Context.TTransferBinOrders.Update(t);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 提交状态
        /// </summary>
        /// <param name="submitTranDTO"></param>
        /// <returns></returns>

        public bool SubmitTranState(SubmitTranDTO submitTranDTO)
        {
            var user = Context.TUsers.Where(u => u.RealName == submitTranDTO.RealName && u.JobNo == submitTranDTO.JoNO).FirstOrDefault();
            if (user != null)
            {
                var tran = Context.TTransferBinOrders.Where(t => t.Id == submitTranDTO.TranId).FirstOrDefault();
                tran.Status = 2;
                if (UpdateTransferBinOrder(tran))
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 删除多条移库明细下物料信息数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>

        public bool DeleteTransferBinOrderDetails(List<int?> ids)
        {
            if (ids == null || ids.Count == 0)
            {
                return false;
            }
            var itemsToRemove = Context.TTransferBinOrderDetails.Where(o => ids.Contains(o.Id)).ToList();; // 找到需要删除的数据
            Context.TTransferBinOrderDetails.RemoveRange(itemsToRemove); // 执行批量删除操作
            int recordsAffected = Context.SaveChanges(); // 保存更改并获取受影响的记录数

            return recordsAffected == ids.Count; // 返回是否成功删除了所有指定的数据

        }
        /// <summary>
        /// 提交移库
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool SubmitTrans(TTransferBinOrderDTO obj)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 移库单导出
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="customerId"></param>
        /// <param name="status"></param>
        /// <param name="warehouseId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TTransferBinOrder> GetExcel(string? ordersn, DateTime? startTime, DateTime? endTime,int? companyId, int? status)
        {
            var list = Context.TTransferBinOrders.AsNoTracking().ToList();
            list = list.OrderByDescending(x => x.CreateDate).ToList();
            // 查找公司
            if (!string.IsNullOrEmpty(ordersn))
            {
                list = list.Where(x => x.OrderSn.Contains(ordersn)).ToList();
            }
            // 查找公司
            if (companyId != 0 && companyId is not null)
            {
                list = list.Where(x => x.CompanyId == companyId).ToList();
            }

            // 查询状态
            if (status is not null)
            {
                list = list.Where(x => x.Status == status).ToList();
            }

            // pda显示收获中和未收货的
            if (status is not null && status == 3)
            {
                list = list.Where(x => x.Status != 2).ToList();
            }

            // 根据时间来筛选
            if (startTime != null && endTime != null)
            {
                list = list.Where(x => x.CreateDate >= startTime && x.CreateDate <= endTime).ToList();
            }

            // pc显示收获中的在上面未收获的在下面
            if (status is not null && status == 4)
            {
                list = list.Where(x => x.Status != 2).OrderByDescending(x => x.Status == 1).ThenByDescending(x => x.Status == 0).ToList();
            }

            return list;
        }

        /// <summary>
        /// 移库任务下传
        /// </summary>
        /// <param name="transferSiglesList"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool TransferTaskDownload(List<TransferSigles> transferSiglesList, out string message)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {                   
                    message = "";                    
                    foreach (var transfertSigles in transferSiglesList)
                    {
                        var tranferBinOrderDetail = new TTransferBinOrderDetail();
                        #region 许佳杰代码
                        //var obj = Context.TTransferBinOrders.Find(transfertSigles.Id);
                        //var transBinOrde = Context.TTransferBinOrders.FirstOrDefault(x => x.OrderId == transfertSigles.Id);
                        //var t = transferSiglesList.Where(x => x.Id == transfertSigles.Id);
                        //if (transBinOrde != null || t.Count() > 1)
                        //{
                        //tranferBinOrderDetail.OrderId = transBinOrde.Id;
                        //tranferBinOrderDetail.OrderSn = transfertSigles.AdjustNo;
                        //tranferBinOrderDetail.MaterialName = transfertSigles.MaterialDesc;
                        //tranferBinOrderDetail.MaterialNo = transfertSigles.MaterialNo;
                        //tranferBinOrderDetail.StoreType = transfertSigles.StoreType;
                        //tranferBinOrderDetail.Factory = transfertSigles.Factory;
                        //tranferBinOrderDetail.StockLocation = transfertSigles.Factory;
                        //tranferBinOrderDetail.StorageArea = transfertSigles.StorageArea;
                        //tranferBinOrderDetail.FromLocationCode = transfertSigles.BinNo;
                        //tranferBinOrderDetail.BaseUnit = transfertSigles.BaseUnit;
                        //tranferBinOrderDetail.BatchNo = transfertSigles.BatchNo;
                        //tranferBinOrderDetail.SupplierName = transfertSigles.SupplierName;
                        //tranferBinOrderDetail.SupplierNo = transfertSigles.SupplierNo;
                        //tranferBinOrderDetail.WbsCode = transfertSigles.WbsCode;
                        //tranferBinOrderDetail.AdjustQuantity = Convert.ToDecimal(transfertSigles.AdjustQuantity);
                        //tranferBinOrderDetail.ToLocationCode = transfertSigles.ToBinNo;
                        //tranferBinOrderDetail.SerialnoParam = transfertSigles.SerialnoParam;
                        //tranferBinOrderDetail.MaterialSerialize = transfertSigles.MaterialSerialize;
                        //receivingBillDetails.Add(receivingBillDetail);
                        //Context.TTransferBinOrderDetails.Add(tranferBinOrderDetail);
                        //continue;
                        //}
                        #endregion
                        var tOrder = new TTransferBinOrder(); 
                        tOrder.OrderId = transfertSigles.Id;
                        tOrder.OrderSn = transfertSigles.AdjustNo;
                        tOrder.Status = 0;
                        tOrder.SourceType = 1;
                        tOrder.Proirity = 0;
                        tOrder.CustomNo = transfertSigles.CustomNo;
                        tOrder.AdjustOporate = transfertSigles.AdjustOporate;
                        tOrder.SalesNo = transfertSigles.SalesNo;   
                        tOrder.SalesLine = transfertSigles.SalesLine;
                        tOrder.CreateDate = DateTime.Now;
                        Context.TTransferBinOrders.Add(tOrder);
                        Context.SaveChanges();
                        tranferBinOrderDetail.OrderId = tOrder.Id;
                        tranferBinOrderDetail.OrderSn = tOrder.OrderSn;
                        tranferBinOrderDetail.Status = 0;
                        tranferBinOrderDetail.StoreType = transfertSigles.StoreType;
                        tranferBinOrderDetail.Factory = transfertSigles.Factory;   
                        tranferBinOrderDetail.FromWhCode = transfertSigles.StorageNo;
                        tranferBinOrderDetail.StorageArea = transfertSigles.StorageArea;
                        tranferBinOrderDetail.FromLocationCode = transfertSigles.BinNo;
                        tranferBinOrderDetail.FromLocationName = transfertSigles.StockLocation;
                        tranferBinOrderDetail.Quantity = (int?)transfertSigles.Quantity;
                        var materobj = Context.TMaterial.AsNoTracking().FirstOrDefault(x => x.Code == transfertSigles.MaterialNo);
                        if (materobj != null)
                        {
                            tranferBinOrderDetail.MaterialId = materobj.Id;
                        }
                        else
                        {
                            TMaterial material = new TMaterial();
                            material.Code = transfertSigles.MaterialNo;
                            material.Name = transfertSigles.MaterialDesc;
                            material.CreateDate = DateTime.Now;
                            Context.TMaterial.Add(material);
                            Context.SaveChanges();
                            tranferBinOrderDetail.MaterialId = material.Id;
                        }
                        var invenobj = Context.TInventory.AsNoTracking().FirstOrDefault(x => x.MaterialCode == transfertSigles.MaterialNo && x.LocationCode == transfertSigles.BinNo);
                        if(invenobj==null)
                        {
                            message = "库存中未找到此物料："+ transfertSigles.MaterialDesc;
                            return false;
                        }
                        //起始仓位
                        var fromcellobj = Context.TCells.AsNoTracking().FirstOrDefault(x => x.Code == transfertSigles.BinNo);
                        if (fromcellobj != null) 
                        {
                            tranferBinOrderDetail.FromLocationId = fromcellobj.Id;
                            tranferBinOrderDetail.FromLocationName= fromcellobj.Name;
                        }
                        else
                        {
                            TCell cell = new TCell();
                            cell.Name = "仓位" + transfertSigles.BinNo;
                            cell.Code= transfertSigles.BinNo;
                            cell.WhCode = transfertSigles.StorageNo;
                            cell.AreaCode = transfertSigles.StorageArea;
                            cell.CellType = 1;
                            cell.Status = 1;
                            cell.LineNo = 1;
                            cell.LayerNo = 1;
                            cell.ColumnNo = 1;
                            cell.DepthIndex = 1;
                            cell.IsMaxDepth = false;
                            cell.CreateDate = DateTime.Now;
                            cell.FullStatus = 0;
                            cell.HeightType = 1;
                            Context.SaveChanges();
                            tranferBinOrderDetail.FromLocationId = cell.Id;
                            tranferBinOrderDetail.FromLocationName = cell.Name;
                        }
                        //目标仓位
                        var tocellobj = Context.TCells.AsNoTracking().FirstOrDefault(x => x.Code == transfertSigles.ToBinNo);
                        if (tocellobj != null)
                        {
                            tranferBinOrderDetail.ToLocationId = tocellobj.Id;
                            tranferBinOrderDetail.ToLocationName = tocellobj.Name;
                        }
                        else
                        {
                            TCell cell = new TCell();
                            cell.Name = "仓位" + transfertSigles.ToBinNo;
                            cell.Code = transfertSigles.ToBinNo;
                            cell.WhCode = transfertSigles.StorageNo;
                            cell.AreaCode = transfertSigles.StorageArea;
                            cell.CellType = 1;
                            cell.Status = 1;
                            cell.LineNo = 1;
                            cell.LayerNo = 1;
                            cell.ColumnNo = 1;
                            cell.DepthIndex = 1;
                            cell.IsMaxDepth = false;
                            cell.CreateDate = DateTime.Now;
                            cell.FullStatus = 0;
                            cell.HeightType = 1;
                            Context.TCells.Add(cell);
                            Context.SaveChanges();
                            tranferBinOrderDetail.ToLocationId = cell.Id;
                            tranferBinOrderDetail.ToLocationName = cell.Name;
                        }
                        tranferBinOrderDetail.MaterialNo = transfertSigles.MaterialNo;
                        tranferBinOrderDetail.MaterialName = transfertSigles.MaterialDesc;
                        tranferBinOrderDetail.BaseUnit = transfertSigles.BaseUnit;
                        tranferBinOrderDetail.BatchNo = transfertSigles.BatchNo;
                        tranferBinOrderDetail.SupplierNo = transfertSigles.SupplierNo;
                        tranferBinOrderDetail.SupplierName = transfertSigles.SupplierName;
                        tranferBinOrderDetail.WbsCode = transfertSigles.WbsCode;
                        tranferBinOrderDetail.StoreMark = transfertSigles.StoreMark;
                        tranferBinOrderDetail.AdjustQuantity = Convert.ToDecimal(transfertSigles.AdjustQuantity);
                        tranferBinOrderDetail.ToLocationCode = transfertSigles.ToBinNo;
                        tranferBinOrderDetail.SerialnoParam = transfertSigles.SerialnoParam;
                        if(transfertSigles.SerialList.Any())
                        {
                            foreach (var item in transfertSigles.SerialList)
                            {
                                tranferBinOrderDetail.MaterialSerialize = item.MaterialSerialize;
                            }
                        }                      
                        Context.TTransferBinOrderDetails.Add(tranferBinOrderDetail);
                    }

                    //提交保存
                    Context.SaveChanges();
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    tran.Rollback();
                    return false;
                    throw;
                }
            }
        }

        /// <summary>
        /// 移库单回传
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TransferSigles> BackTransferSigles()
        {
            List<TransferSigles> tlist = new List<TransferSigles>();
            //移库单
            var translist = Context.TTransferBinOrders.AsNoTracking().Where(x => x.Status == 4).OrderBy(x => x.CreateDate);
            if(translist.Any())
            {             
                foreach (var item in translist)
                {
                    TransferSigles tobj = new TransferSigles();
                    tobj.Id = item.OrderId;
                    tobj.AdjustNo = item.OrderSn;                
                    tobj.CustomNo=item.CustomNo;
                    tobj.SalesNo=item.SalesNo;
                    tobj.SalesLine = item.SalesLine;
                    tobj.AdjustOporate = item.AdjustOporate;

                    //移库单id
                    var tranorlist = Context.TTransferBinOrderDetails.AsNoTracking().Where(x => x.OrderId == item.Id);
                    if(tranorlist.Any())
                    {
                        foreach (var item2 in tranorlist)
                        {
                            SerialLists serobj = new SerialLists();
                            tobj.StoreType = item2.StoreType;
                            tobj.Factory = item2.Factory;
                            tobj.StockLocation = item2.StockLocation;
                            tobj.StorageNo = item2.FromWhCode;
                            tobj.StorageArea=item2.StorageArea;
                            tobj.BinNo = item2.FromLocationCode;
                            tobj.Quantity = item2.Quantity==null?0: (double)item2.Quantity;
                            tobj.MaterialNo = item2.MaterialNo;
                            tobj.MaterialDesc = item2.MaterialDesc;
                            tobj.BaseUnit = item2.BaseUnit;
                            tobj.BatchNo = item2.BatchNo;
                            tobj.SupplierNo = item2.SupplierNo;
                            tobj.SupplierName = item2.SupplierName;
                            tobj.WbsCode = item2.WbsCode;
                            tobj.StoreMark = item2.StoreMark;
                            tobj.AdjustQuantity = (double)item2.AdjustQuantity;
                            tobj.ToBinNo = item2.ToLocationCode;
                            tobj.SerialnoParam = item2.SerialnoParam;
                            serobj.MaterialSerialize = item2.MaterialSerialize;
                            tobj.SerialList.Add(serobj);
                            tlist.Add(tobj);
                        }
                    }
                }
                return tlist;
            }
            return null;
        }

        public async Task<bool> PostTransferBin(MESTransferBinDto dto)
        {
            // 使用 HttpClient 来发送 HTTP 请求
            using (HttpClient client = new HttpClient())
            {
                try
                {

                    //接口地址(待确认)
                    string apiUrl = "127.0.0.1:8080/dts/wmsapi/relocation/insert";
                    string jsonData = JsonConvert.SerializeObject(dto);
                    StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                    // 发送 POST 请求到指定的 API 地址
                    HttpResponseMessage response = await client.PostAsync(apiUrl, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine("Response: " + responseBody);
                        return true;
                    }
                    else
                    {
                        Console.WriteLine("未能调用API。状态代码: " + response.StatusCode);
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("出现错误: " + ex.Message);
                    return false;
                }
            }
        }
    }
}

 